<template>
  <el-card class="box-card">
    <el-upload
      class="upload-demo"
      drag
      multiple
      :auto-upload="false"
      accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel"
      :file-list="fileListUpload"
      :limit="limitUpload"
      :on-change="handleChange"
    >
      <el-icon class="el-icon--upload">
        <UploadFilled />
      </el-icon>
      <div class="el-upload__text">拖拽上传 或者 <em>点击上传</em></div>
      <template #tip>
        <div class="el-upload__tip">
          <h3>** 只支持上传 xlsx 文件</h3>
          <h3>
            ** excel表格必须包含<span style="color: red"
              >ID 字段（大小写也要保持一致），标题字段，内容字段</span
            >
          </h3>
          <!-- <h3>** 手动删除已上传的文件，才能重新上传</h3> -->
        </div>
      </template>
    </el-upload>
  </el-card>
</template>
<script lang="ts">
import * as XLSX from "xlsx";
import { ElMessage } from "element-plus";
import { defineComponent } from "vue";

export default defineComponent({
  data() {
    return {
      limitUpload: 1,
      fileListUpload: [],
      fileData: [],
    };
  },

  methods: {
    handleChange(file: any) {
      if (
        file.raw.type !==
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
      ) {
        ElMessage.error("只能上传 xlsx/xls 文件");
        return false;
      } else if (file.size / 1024 / 1024 > 5) {
        ElMessage.error("上传的文件不能超过5M");
        return false;
      }
      this.importExcelData(file.raw);
    },
    async gotoListPage(data: any) {
      this.$emit("fileImportResult", data);
    },
    importExcelData(obj: any) {
      let that = this;
      // 通过DOM取文件数据
      let rABS = false; //是否将文件读取为二进制字符串
      let file = obj;
      let reader = new FileReader();
      FileReader.prototype.readAsBinaryString = function (f) {
        let binary = "";
        let wb; //读取完成的数据
        let outdata;
        let reader = new FileReader();
        reader.onload = function (e) {
          let bytes = new Uint8Array(reader.result as ArrayBuffer);
          let length = bytes.byteLength;
          for (let i = 0; i < length; i++) {
            binary += String.fromCharCode(bytes[i]);
          }

          wb = XLSX.read(binary, {
            type: "binary",
          });
          outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]); //outdata就是你想要的东西
          that.fileData = outdata as any; // 类型断言：手动指定一个值的类型（相当于类型转换）
          that.gotoListPage(that.fileData);
        };
        reader.readAsArrayBuffer(f);
      };
      reader.readAsBinaryString(file);
    },
  },
});
</script>
<script setup lang="ts">
import { UploadFilled } from "@element-plus/icons-vue";
</script>
<style scoped>
.box-card {
  height: 100%;
  box-sizing: border-box;
}
.upload-demo {
  height: 100%;
}
</style>
